/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pa165.library.backend;

import cz.muni.fi.pa165.library.api.ReaderService;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;

import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;





/**
 *
 * @author dulinka
 */
public class LibraryUserDetailsService implements UserDetailsService{

    private ReaderDAO readerDAO;  
    private UserDAO userDAO;  
    
    public void setReaderDAO(ReaderDAO readerDAO) {
        this.readerDAO = readerDAO;
    }
    
    public void setUserDAO(UserDAO userDAO) {
        this.userDAO = userDAO;
    }
    
    @Override
    @Transactional(readOnly=true)
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
        cz.muni.fi.pa165.library.backend.User user = userDAO.findUserByEmail(email);
        List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>(2);
        String pass;
        if (user != null){
            pass = user.getPassword();
            authList.add(new GrantedAuthorityImpl("ROLE_LIBRARIAN"));
            authList.add(new GrantedAuthorityImpl("ROLE_READER"));
        }else{
            Reader reader = readerDAO.findReaderByEmail(email);
            if (reader == null){throw new UsernameNotFoundException("Username Not Found");}
            pass = reader.getPassword();
            authList.add(new GrantedAuthorityImpl("ROLE_READER"));    
        }
         return new User(email, pass, true, true, true, true, authList);


        
    }    

}
